//
//  AiRoleBean.swift
//  imprint
//
//  Created by 小柠檬🍋 on 2025/1/8.
//

import Foundation
import LeanCloud
import GRDB

//日记
class DiaryBean : ICloudTable, IDbTable, Identifiable {
    
    static let databaseTableName = "diary"
    
    func getCloudTable() -> String {
        return "Diary"
    }
    
    
    //leanCloud 排除字段
    func doCustomExcluded() -> [String? : Any?] {
        return doExcluded(subject: self, excluded: ["tagName","listDiaryPicture","tem1","temOther","createTime","updateTime","modifySign"])
    }
    //db排除字段
    func doCustomDBExcluded()  -> [String? : Any?] {
        return doExcluded(subject: self, excluded: ["tagName","listDiaryPicture","tem1","temOther"])
    }
    
    
    init(content: String) {
        self.content = content
    }
    
    init(content: String,time: Int64) {
        self.content = content
        self.time = time
    }
    
    var objectId: String?
    var title: String?
    var content: String? // 内容
    var letterNum: String? = nil//字母数值，替代initials
    var userId: String?
    var mood:Int = IMoodType.NO.rawValue //时间
    var time: Int64 = 0 //时间
    var tagId: String? = nil //标签id
    var sound: SoundBean? = nil//语音
    var location: LocationBean? = nil//位置
    var roleType: Int = IRoleType.USER.rawValue //角色类型
    var aiChat:String? = nil//废弃
    var aiChat2: AiChatHistoryBean? = nil
    var roleId : String? = nil
    var status : Int = IStatusType.NORMAL.rawValue
    var count: Int = 0//字数
    var closeComment: Bool? = false //关闭评论
    var commentCount: Int? = 0 //评论数量
    var aiRule: AiRuleBean? = nil
    var diaryType: String? = nil
    var createTime: Int64? = nil//创建时间
    var updateTime: Int64? = nil//更新时间
    var modifySign: Bool? = nil//修改标识
    var bubbleId:String? = nil
    var memory: Bool? = nil//是否提取记忆

    // 以下没有该字段，需要手动添加
    var tagName:String? //标签,
    var listDiaryPicture: [CloudPictureBean]? = nil//图片列表
    var tem1: DiaryTemComment? = nil //评论使用, ai的主动回应的评论，，如果是ai日记，则取评论第一条
    var temOther: [DiaryTemComment]? = nil //其他的评论
    
    func setChatAiAll(aiRole: AiRoleBean?, value: String?) {
        addDiaryAi(aiRole: aiRole, text: value)
    }
    
    func setNewChatAiAll(aiRoleId: String, value: String?) {
        addNewDiaryAi(aiRoleId: aiRoleId,text: value)
    }
    
    private func addDiaryAi(aiRole: AiRoleBean?, text: String?) {
        if aiChat2 == nil {
            aiChat2 = AiChatHistoryBean()
        }
        if aiChat2?.listChat == nil {
            aiChat2?.listChat = []
        }
        aiChat2?.text = text
        aiChat2?.aiRole = aiRole
        let count = (aiChat2?.listChat?.count ?? 0)
        if (count > 5) {
            showLog("数量为：\(count)")
            aiChat2?.listChat?.remove(at: (count - 1))
        }
        let bean = AiChatHistoryBean()
        bean.aiRole = aiRole
        bean.text = text
        aiChat2?.listChat?.insert(bean, at: 0)
    }
    
    func addNewDiaryAi(aiRoleId: String, text: String?) {
        var list = aiRule?.listAiRole
        if list == nil || list!.isEmpty {
            // 如果为空，则添加
            let listAiRole = [AiReplyBean(roleId: aiRoleId)]
            aiRule?.listAiRole = listAiRole
            list = aiRule?.listAiRole ?? []
        }
        for bean in list! {
            showLog("checkDiaryReply")
            showLog("\(String(describing: bean.roleId)):\(aiRoleId)")
            if bean.roleId == aiRoleId {
                // 存在相同的则移除
                if let content = bean.content, let firstIndex = content.firstIndex(of: text ?? "") {
                    bean.content?.remove(at: firstIndex)
                }
                // 超过5个移除
                if let content = bean.content, content.count > 5 {
                    bean.content?.remove(at: content.count - 1)
                }
                if bean.content == nil {
                    bean.content = []
                }
                bean.content?.insert(text ?? "", at: 0)
                return
            }
        }
    }
    
    
    //是否是多人回复
    func isMultiple() -> Bool {
         //注意是不为null，如果是数组为空，则也是多选。
        return aiRule?.listAiRole != nil
     }
    
    //旧版本ai回复
    func getAiText() -> String? {
        return aiChat2?.text ?? aiChat
    }
    
    //根据角色，获取该ai的回复
    func getAiReply(aiRoleId: String) -> String {
        var topString = ""
        topString = aiRule?.listAiRole?.first { $0.roleId == aiRoleId }?.content?[0] ?? ""
        
        if (topString.isEmpty) {
            topString = aiChat2?.text ?? ""
         }
         return topString
     }
    
    //是否展开更多评论
    func showMoreComment() -> Bool {
         if (isMultiple()) {
             //多人回复需要大于，人数*2
             return (temOther?.count ?? 0) >= (aiRule?.listAiRole?.count ?? 0) * 2
         }
         return (temOther?.count ?? 0) >= 3
     }
}

extension DiaryBean {
    // db数据库指定字段
    public func encode(to container: inout PersistenceContainer) {
        doDBExcluded(to: &container)
    }
}
